package filter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/admin/*")
public class AdminFilter extends BaseFilter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // Set request encoding and response content type with charset
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // Check for an existing admin session
        HttpSession session = request.getSession(false); // Do not create if it doesn't exist
        Object admin = session != null ? session.getAttribute("admin") : null;

        // Check the URI and action parameters
        String uri = request.getRequestURI();
        String action = request.getParameter("action");

        // Permit access to the login page and login action without being logged in
        if (uri.endsWith("adminLogin.html") || "adminLogin".equals(action)) {
            filterChain.doFilter(request, response);
            return;
        }

        // Only proceed if the user is logged in as an admin
        if (admin != null) {
            filterChain.doFilter(request, response);
        } else {
            // Redirect to login page if not authenticated
            response.sendRedirect("/admin/adminLogin.html");
        }
    }
}
